<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新闻管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 配置Tailwind自定义主题 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        neutral: '#F5F7FA',
                        dark: '#1D2129',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .btn-hover {
                @apply transition-all duration-300 hover:shadow-lg transform hover:-translate-y-0.5;
            }
            .input-focus {
                @apply focus:ring-2 focus:ring-primary/30 focus:border-primary focus:outline-none;
            }
            .news-card-cursor {
                @apply cursor-pointer transition-all duration-300 hover:shadow-xl;
            }
        }
    </style>
</head>
<body class="font-inter bg-neutral min-h-screen text-dark">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm sticky top-0 z-50">
    <div class="container mx-auto px-4 py-4 flex justify-between items-center">
        <h1 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-primary flex items-center">
            <i class="fa fa-newspaper-o mr-2"></i>
            新闻管理系统
        </h1>

        <!-- 搜索框区域 -->
        <div class="w-full max-w-xl relative">
            <input
                    type="text"
                    placeholder="搜索新闻..."
                    class="w-full py-2 px-4 pr-10 rounded-lg border border-gray-200 input-focus transition-all"
                    id="searchInput"
            >
            <button class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-primary transition-colors" id="searchBtn">
                <i class="fa fa-search text-lg"></i>
            </button>
        </div>

        <!-- 添加新闻按钮 -->
        <button id="addNewsBtn" class="ml-4 bg-primary text-white py-2 px-6 rounded-lg btn-hover flex items-center">
            <i class="fa fa-plus mr-2"></i>
            添加新闻
        </button>
    </div>
</header>

<main class="container mx-auto px-4 py-8">
    <!-- 新闻列表标题 -->
    <div class="mb-6 flex justify-between items-center">
        <h2 class="text-xl font-semibold">新闻列表</h2>
        <span class="text-gray-500 text-sm" id="newsCount">共 0 条新闻</span>
    </div>

    <!-- 新闻列表容器 -->
    <div id="newsList" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <!-- 新闻卡片会通过JavaScript动态添加 -->
        <div class="col-span-full text-center py-16 text-gray-500">
            <i class="fa fa-file-text-o text-5xl mb-4 opacity-30"></i>
            <p>暂无新闻数据，请添加新闻</p>
        </div>
    </div>
</main>

<!-- 添加新闻模态框 -->
<div id="newsModal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center opacity-0 pointer-events-none transition-opacity duration-300">
    <div class="bg-white rounded-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto transform scale-95 transition-transform duration-300">
        <div class="p-6 border-b">
            <div class="flex justify-between items-center">
                <h3 class="text-xl font-semibold">添加新闻信息</h3>
                <button id="closeModal" class="text-gray-400 hover:text-gray-600 transition-colors">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
        </div>

        <form id="newsForm" class="p-6 space-y-5">
            <!-- 标题输入 -->
            <div>
                <label for="title" class="block text-sm font-medium text-gray-700 mb-1">标题</label>
                <input
                        type="text"
                        id="title"
                        required
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus"
                        placeholder="请输入新闻标题"
                >
            </div>

            <!-- 作者输入 -->
            <div>
                <label for="author" class="block text-sm font-medium text-gray-700 mb-1">作者</label>
                <input
                        type="text"
                        id="author"
                        required
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus"
                        placeholder="请输入作者名称"
                >
            </div>

            <!-- 分类选择 -->
            <div>
                <label for="category" class="block text-sm font-medium text-gray-700 mb-1">分类</label>
                <select
                        id="category"
                        required
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus"
                >
                    <option value="">请选择分类</option>
                    <option value="国内">国内新闻</option>
                    <option value="国际">国际新闻</option>
                    <option value="科技">科技新闻</option>
                    <option value="娱乐">娱乐新闻</option>
                    <option value="体育">体育新闻</option>
                </select>
            </div>

            <!-- 正文输入 -->
            <div>
                <label for="content" class="block text-sm font-medium text-gray-700 mb-1">正文</label>
                <textarea
                        id="content"
                        rows="6"
                        required
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg input-focus resize-none"
                        placeholder="请输入新闻正文内容"
                ></textarea>
            </div>

            <!-- 提交按钮 -->
            <div class="pt-4 flex justify-end">
                <button
                        type="submit"
                        class="bg-primary text-white py-2 px-6 rounded-lg btn-hover flex items-center"
                >
                    <i class="fa fa-save mr-2"></i>
                    添加新闻
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 新闻详情模态框 -->
<div id="newsDetailModal" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center opacity-0 pointer-events-none transition-opacity duration-300">
    <div class="bg-white rounded-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto transform scale-95 transition-transform duration-300">
        <!-- 详情模态框头部 -->
        <div class="p-6 border-b flex justify-between items-center">
            <h3 class="text-xl font-semibold">新闻详情</h3>
            <button id="closeDetailModal" class="text-gray-400 hover:text-gray-600 transition-colors">
                <i class="fa fa-times text-xl"></i>
            </button>
        </div>

        <!-- 详情内容区域（默认加载状态） -->
        <div class="p-6 space-y-6" id="detailContentWrapper">
            <div class="text-center py-12">
                <i class="fa fa-spinner fa-spin text-3xl text-primary mb-4"></i>
                <p class="text-gray-500">正在加载详情...</p>
            </div>
        </div>
    </div>
</div>

<script>
    // 获取DOM元素
    const addNewsBtn = document.getElementById('addNewsBtn');
    const newsModal = document.getElementById('newsModal');
    const closeModal = document.getElementById('closeModal');
    const newsForm = document.getElementById('newsForm');
    const newsList = document.getElementById('newsList');
    const newsCount = document.getElementById('newsCount');
    const newsDetailModal = document.getElementById('newsDetailModal');
    const closeDetailModal = document.getElementById('closeDetailModal');
    const detailContentWrapper = document.getElementById('detailContentWrapper');
    const searchInput = document.getElementById('searchInput'); // 新增：搜索输入框
    const searchBtn = document.getElementById('searchBtn');     // 新增：搜索按钮

    // 存储新闻数据
    let newsData = [];

    // 打开添加新闻模态框
    function openModal() {
        newsModal.classList.remove('opacity-0', 'pointer-events-none');
        newsModal.querySelector('div').classList.remove('scale-95');
        newsModal.querySelector('div').classList.add('scale-100');
        newsForm.reset();
    }

    // 关闭添加新闻模态框
    function closeModalFunc() {
        newsModal.classList.add('opacity-0', 'pointer-events-none');
        newsModal.querySelector('div').classList.remove('scale-100');
        newsModal.querySelector('div').classList.add('scale-95');
    }

    // 关闭详情模态框
    function closeDetailModalFunc() {
        newsDetailModal.classList.add('opacity-0', 'pointer-events-none');
        newsDetailModal.querySelector('div').classList.remove('scale-100');
        newsDetailModal.querySelector('div').classList.add('scale-95');
    }

    // 核心修改：从卡片元素中读取ID，请求后端详情
    async function openNewsDetailByCard(newsId) {
        // 校验ID有效性
        if (!newsId || isNaN(parseInt(newsId))) {
            showNotification('新闻ID无效，无法加载详情');
            return;
        }

        // 2. 显示加载状态和详情模态框
        detailContentWrapper.innerHTML = `
            <div class="text-center py-12">
                <i class="fa fa-spinner fa-spin text-3xl text-primary mb-4"></i>
                <p class="text-gray-500">正在加载详情...</p>
            </div>
        `;
        newsDetailModal.classList.remove('opacity-0', 'pointer-events-none');
        newsDetailModal.querySelector('div').classList.remove('scale-95');
        newsDetailModal.querySelector('div').classList.add('scale-100');

        // 3. 调用后端详情接口
        try {
            const response = await fetch(`/news/news/${newsId}`);
            const jsonData = await response.json();
            console.log('新闻详情数据：', jsonData);
            if (jsonData.code === 200) {
                // 渲染详情内容
                renderNewsDetail(jsonData.data);
            } else {
                throw new Error(jsonData.message);
            }
        } catch (error) {
            console.error('加载新闻详情错误：', error);
            detailContentWrapper.innerHTML = `
                <div class="text-center py-12">
                    <i class="fa fa-exclamation-circle text-3xl text-red-500 mb-4"></i>
                    <p class="text-gray-500">加载详情失败，请刷新页面重试</p>
                    <button onclick="closeDetailModalFunc()" class="mt-4 bg-primary text-white py-2 px-4 rounded-lg btn-hover">
                        关闭
                    </button>
                </div>
            `;
        }
    }

    // 渲染新闻详情内容
    function renderNewsDetail(news) {
        detailContentWrapper.innerHTML = `
            <h2 class="text-2xl font-bold text-dark">${news.title}</h2>
            <div class="flex flex-wrap gap-4 text-gray-500 text-sm">
                <span><i class="fa fa-user mr-1"></i> ${news.author}</span>
                <span><i class="fa fa-folder-o mr-1"></i> ${news.classify}</span>
                <span><i class="fa fa-clock-o mr-1"></i> ${news.createdTime}</span>
            </div>
            <div class="text-gray-700 leading-relaxed whitespace-pre-line border-t border-gray-100 pt-4">
                ${news.text}
            </div>
            <div class="flex justify-end pt-4 border-t border-gray-100">
                <button onclick="closeDetailModalFunc()" class="bg-gray-200 hover:bg-gray-300 text-dark py-2 px-6 rounded-lg btn-hover flex items-center">
                    <i class="fa fa-times mr-2"></i>
                    关闭
                </button>
            </div>
        `;
    }

    // 添加新闻
    async function addNews(e) {
        e.preventDefault();
        const title = document.getElementById('title').value;
        const author = document.getElementById('author').value;
        const classify = document.getElementById('category').value;
        const text = document.getElementById('content').value;

        if (!title || !author || !classify || !text) {
            showNotification('请填写完整的新闻信息！');
            return;
        }

        try {
            const response = await fetch("/news/publish", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ title, author, classify, text })
            });
            const data = await response.json();

            if (data.code === 200) {
                renderNewsList();
                closeModalFunc();
                showNotification('新闻添加成功！');
            } else {
                showNotification('添加失败：' + (data.data || '未知错误'));
            }
        } catch (error) {
            console.error('添加新闻错误：', error);
            showNotification('添加新闻失败！');
        }
    }

    // 核心修改：渲染卡片时，通过data-id存储新闻ID
    async function renderNewsList() {
        try {
            const response = await fetch("/news/news");
            const jsonData = await response.json();
            console.log(jsonData)
            newsData = jsonData.data || [];
            newsCount.textContent = `共 ${newsData.length} 条新闻`;
            newsList.innerHTML = '';

            if (newsData.length === 0) {
                newsList.innerHTML = `
              <div class="col-span-full text-center py-16 text-gray-500">
                <i class="fa fa-file-text-o text-5xl mb-4 opacity-30"></i>
                <p>暂无新闻数据，请添加新闻</p>
              </div>
            `;
                return;
            }

            // 遍历渲染卡片：给每个卡片添加data-id属性存储新闻ID
            newsData.forEach(news => {
                const newsCard = document.createElement('div');
                // 关键：通过data-id存储新闻ID，后续点击时读取
                newsCard.setAttribute('data-id', news.newsId);
                newsCard.className = 'bg-white rounded-xl overflow-hidden card-shadow news-card-cursor';
                // 点击卡片时，将当前卡片元素传入函数
                newsCard.onclick = function() {
                    openNewsDetailByCard(news.newsId); // this即当前卡片元素
                };

                newsCard.innerHTML = `
              <div class="p-5">
                <div class="flex justify-between items-start mb-3">
                  <span class="px-2 py-1 bg-primary/10 text-primary text-xs rounded-full">${news.classify}</span>
                  <span class="text-gray-400 text-xs">${news.createdTime}</span>
                </div>
                <h3 class="text-lg font-semibold mb-2 line-clamp-2 hover:text-primary transition-colors">${news.title}</h3>
                <p class="text-gray-600 text-sm mb-3 line-clamp-3">${news.text}</p>
                <div class="flex justify-between items-center text-sm">
                  <span class="text-gray-500"><i class="fa fa-user mr-1"></i>${news.author}</span>
                  <button class="text-gray-400 hover:text-red-500 transition-colors delete-btn"
                          data-id="${news.newsId}"
                          onclick="event.stopPropagation()">
                    <i class="fa fa-trash-o"></i>
                  </button>
                </div>
              </div>
            `;
                newsList.appendChild(newsCard);
            });

            // 绑定删除事件
            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const id = parseInt(this.getAttribute('data-id'));
                    deleteNews(id);
                });
            });
        } catch (error) {
            console.error('渲染新闻列表错误：', error);
            newsList.innerHTML = `
              <div class="col-span-full text-center py-16 text-gray-500">
                <i class="fa fa-exclamation-circle text-5xl mb-4 opacity-30"></i>
                <p>加载新闻失败，请刷新页面重试</p>
              </div>
            `;
        }
    }

    async function searchNewsByKeyword(searchKeyword) {
        if (!searchKeyword) {
            renderNewsList();
        }
        const response = await fetch(`/news/search/${searchKeyword}`);
        const jsonData = await response.json();
        newsData = jsonData.data || [];
        newsCount.textContent = `共 ${newsData.length} 条新闻`;
        newsList.innerHTML = ''; // 清空列表
        if (newsData.length === 0) {
            // 无数据时显示提示（区分“无搜索结果”和“无新闻”）
            const tipText = searchKeyword ? '未找到匹配的新闻' : '暂无新闻数据，请添加新闻';
            newsList.innerHTML = `
              <div class="col-span-full text-center py-16 text-gray-500">
                <i class="fa fa-file-text-o text-5xl mb-4 opacity-30"></i>
                <p>${tipText}</p>
              </div>
            `;
            return;
        }

        newsData.forEach(news => {
            const newsCard = document.createElement('div');
            newsCard.className = 'bg-white rounded-xl overflow-hidden card-shadow news-card-cursor';
            newsCard.onclick = function () {
                openNewsDetailByCard(news.newsId);
            };

            // 新增：对标题、作者、正文、分类进行关键字高亮处理
            const highlightedTitle = highlightKeyword(news.title, searchKeyword);
            const highlightedText = highlightKeyword(news.text, searchKeyword);
            const highlightedAuthor = highlightKeyword(news.author, searchKeyword);
            const highlightedClassify = highlightKeyword(news.classify, searchKeyword);


            newsCard.innerHTML = `
              <div class="p-5">
                <div class="flex justify-between items-start mb-3">
                  <!-- 1. 分类高亮（直接使用高亮后的HTML字符串） -->
                  <span class="px-2 py-1 bg-primary/10 text-primary text-xs rounded-full">
                    ${highlightedClassify}
                  </span>
                  <span class="text-gray-400 text-xs">${news.createdTime}</span>
                </div>
                <!-- 2. 标题高亮 -->
                <h3 class="text-lg font-semibold mb-2 line-clamp-2 hover:text-primary transition-colors">
                  ${highlightedTitle}
                </h3>
                <!-- 3. 正文高亮 -->
                <p class="text-gray-600 text-sm mb-3 line-clamp-3">
                  ${highlightedText}
                </p>
                <div class="flex justify-between items-center text-sm">
                  <!-- 4. 作者高亮 -->
                  <span class="text-gray-500">
                    <i class="fa fa-user mr-1"></i>${highlightedAuthor}
                  </span>
                  <button class="text-gray-400 hover:text-red-500 transition-colors delete-btn"
                          data-id="${news.newsId}"
                          onclick="event.stopPropagation()">
                    <i class="fa fa-trash-o"></i>
                  </button>
                </div>
              </div>
            `;
            newsList.appendChild(newsCard);
        });

    }

    // 删除新闻
    function deleteNews(id) {
        if (isNaN(id) || !confirm('确定要删除这条新闻吗？')) return;

        fetch(`/news/news/${id}`, { method: 'DELETE' })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    newsData = newsData.filter(news => news.newsId !== id);
                    renderNewsList();
                    showNotification('新闻已删除');
                } else {
                    showNotification('删除失败：' + (data.msg || '未知错误'));
                }
            })
            .catch(error => {
                console.error('删除新闻错误：', error);
                showNotification('删除新闻失败！');
            });
    }

    // 新增：关键字高亮函数（参数：原文、关键字，返回带高亮标签的HTML）
    function highlightKeyword(text, keyword) {
        if (!keyword || keyword.trim() === '') return text; // 无关键字时直接返回原文
        // 转义特殊字符（避免正则报错），不区分大小写匹配
        const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        const regex = new RegExp(`(${escapedKeyword})`, 'gi');
        // 用红色背景标签包裹匹配的关键字（不影响原有样式）
        return text.replace(regex, '<span class="bg-red-100 text-red-600 px-0.5 rounded">$1</span>');
    }

    // 显示通知提示
    function showNotification(message) {
        const notification = document.createElement('div');
        notification.className = 'fixed bottom-5 right-5 bg-dark text-white px-4 py-2 rounded-lg shadow-lg transform translate-y-10 opacity-0 transition-all duration-300 z-50';
        notification.textContent = message;
        document.body.appendChild(notification);

        setTimeout(() => {
            notification.classList.remove('translate-y-10', 'opacity-0');
        }, 100);

        setTimeout(() => {
            notification.classList.add('translate-y-10', 'opacity-0');
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }

    // 事件监听
    addNewsBtn.addEventListener('click', openModal);
    closeModal.addEventListener('click', closeModalFunc);
    newsForm.addEventListener('submit', addNews);
    closeDetailModal.addEventListener('click', closeDetailModalFunc);

    // 新增：点击搜索按钮触发搜索
    searchBtn.addEventListener('click', function() {
        const keyword = searchInput.value.trim();
        searchNewsByKeyword(keyword); // 传入关键字，渲染搜索结果（覆盖原有列表）
    });

    // 新增：按回车键触发搜索
    searchInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') { // 检测回车键
            const keyword = searchInput.value.trim();
            searchNewsByKeyword(keyword);
        }
    });


    // 点击模态框外部关闭
    newsModal.addEventListener('click', e => e.target === newsModal && closeModalFunc());
    newsDetailModal.addEventListener('click', e => e.target === newsDetailModal && closeDetailModalFunc());

    // 初始化页面
    renderNewsList();
</script>
</body>
</html>